<!--
 * @Description: 脚本任务配置
 * @Author: DHL
 * @Date: 2022-08-04 10:45:32
 * @LastEditors: DHL
 * @LastEditTime: 2023-01-16 17:15:23
-->
<template>
  <div class="process-panel-tab__content">
    <el-form ref="dbFormRef" :model="dbForm" label-width="80px">
      <el-form-item label="脚本格式" key="scriptFormat">
        <el-input v-model="dbForm.scriptFormat" clearable @change="handleUpdateElementTask" />
      </el-form-item>

      <el-form-item label="脚本类型" key="scriptType">
        <el-select v-model="dbForm.scriptType">
          <el-option label="内联脚本" value="inline" />
          <el-option label="外部脚本" value="external" />
        </el-select>
      </el-form-item>

      <el-form-item label="脚本" v-if="dbForm.scriptType === 'inline'" key="script">
        <el-input
          v-model="dbForm.script"
          autosize
          type="textarea"
          :rows="3"
          clearable
          @change="handleUpdateElementTask"
        />
      </el-form-item>

      <el-form-item label="资源地址" v-if="dbForm.scriptType === 'external'" key="resource">
        <el-input
          v-model="dbForm.resource"
          autosize
          type="textarea"
          :rows="3"
          clearable
          @change="handleUpdateElementTask"
        />
      </el-form-item>

      <el-form-item label="结果变量" key="resultVariable">
        <el-input
          v-model="dbForm.resultVariable"
          autosize
          type="textarea"
          :rows="3"
          clearable
          @change="handleUpdateElementTask"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { useBpmnStore } from '../../../store/bpmn'
  const bpmnStore = useBpmnStore()

  watch(
    () => bpmnStore.activatedElementId,
    (newVal) => {
      if (newVal) {
        nextTick(() => {
          handleResetTaskForm()
        })
      }
    },
    {
      immediate: true
    }
  )

  const dbForm = reactive({
    scriptFormat: '', // 脚本格式
    scriptType: '', // 脚本类型
    script: '', // 脚本
    resource: '', // 资源地址
    resultVariable: '' // 结果变量
  })

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////
  /**
   *
   */
  function handleResetTaskForm() {
    for (let key in dbForm) {
      dbForm[key] = bpmnStore.getActivatedElementBusinessObject(key) || dbForm[key]
    }

    dbForm.scriptType = dbForm.script ? 'inline' : 'external'
  }

  /**
   * 设置脚本表单
   */
  function handleUpdateElementTask() {
    let taskAttr = Object.create(null)
    taskAttr.scriptFormat = dbForm.scriptFormat || null
    taskAttr.resultVariable = dbForm.resultVariable || null

    if (dbForm.scriptType === 'inline') {
      taskAttr.script = dbForm.script || null
      taskAttr.resource = null
    } else {
      taskAttr.resource = dbForm.resource || null
      taskAttr.script = null
    }

    bpmnStore.updateProperties(taskAttr)
  }
</script>

<style scoped lang="scss"></style>
